<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\common\library;

class Aes
{
    private $secretKey;
    private $method;
    private $iv;

    public function __construct($key, $method = 'AES-128-CBC', $iv = null)
    {
        $this->secretKey = $key;
        $this->method = $method;
        $this->iv = $iv;
    }

    public function encrypt($data)
    {
        $iv = $this->iv ?: openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->method));
        $encrypted = openssl_encrypt($data, $this->method, $this->secretKey, 0, $iv);
        return base64_encode($encrypted . '::' . $iv);
    }

    public function decrypt($data)
    {
        list($encryptedData, $iv) = explode('::', base64_decode($data), 2);
        return openssl_decrypt($encryptedData, $this->method, $this->secretKey, 0, $iv);
    }
}